package com.snail.common.toolUtil.number;

/**
 * 数字算法工具类
 *
 * @Author: houyanfeng 2019/1/29
 */
public class NumberCalculateUtil {

    /**
     * 模2除法实现
     *
     * @param dividendStr 被除数，二进制字符串
     * @param divisorStr  除数，二进制字符串
     * @return 商和余数
     */
    public static String mo2(String dividendStr, String divisorStr) {
        char[] dividend = dividendStr.toCharArray();
        char[] divisor = divisorStr.toCharArray();
        String result = "";//最终结果
        String median = "";
//        System.out.println("dividend 计算前 "+median);
        for (int i = 0; i < dividend.length; i++) {
            int len = divisor.length - median.length();
            if (len > 0) {
                median = median + dividend[i];
            }
            if (median.length() == divisor.length) {
                result += "1";
//                System.out.println("dividend 补全后 " + median);

                median = qumo(median.toCharArray(), divisor);
//                System.out.println("dividend 计算后 " + median);
                if (median.startsWith("0")) {
                    if (median.indexOf("1") > 0) {//说明未整除
                        median = median.substring(median.indexOf("1"));
//                        System.out.println(i+" 去0后 " + median);
                    } else {

                    }
                }
            } else {
                result += "0";
            }
        }
        result = result.substring(result.indexOf("1"));
//        System.out.println("result = "+result+", 余数="+median);
//        return  result+","+median;
        return median;
    }


    public static String qumo(char[] dividend, char[] divisor) {
        String result = "";
        for (int j = 0; j < divisor.length; j++) {
            if (dividend[j] == divisor[j]) {
                result += "0";
            } else {
                result += "1";
            }
        }
        return result;
    }
}
